<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
 *
 * functions.php template file
 *
 * (c) 2009 by Mike Walsh
 *
 * @author Mike Walsh <mike_walsh@mindspring.com>
 * @package sandbox-lego
 * @subpackage Sandbox
 * @version $Revision$
 * @lastmodified $Author$
 * @lastmodifiedby $Date$
 *
 */

require_once("sandbox/functions.php") ;

//  The TEMPLATEPATH constant can't be used for child
//  themes as it returns the parent theme path so we
//  need to figure out what CASLTTHEMEPATH is ...

define("CASLTHEMEPATH", sprintf("/%s/themes/%s",
    basename(WP_CONTENT_DIR), basename(dirname(__FILE__)))) ;

//  Define constants to drive the theme options page.
//  These values are important and should not be changed
//  as they drive the selection of the proper header
//  image and CSS file.

define('CASL_THEME_LEAGUE_LOGO_CASL', 'CASL') ;
define('CASL_THEME_LEAGUE_LOGO_RECREATIONAL', 'Recreational') ;
define('CASL_THEME_LEAGUE_LOGO_CHALLENGE', 'Challenge') ;
define('CASL_THEME_LEAGUE_LOGO_CLASSIC', 'Classic') ;
define('CASL_THEME_LEAGUE_LOGO_YTS', 'YTS') ;
define('CASL_THEME_LEAGUE_LOGO_AMBASSADORS', 'Ambassadors') ;

define('CASL_THEME_LEAGUE_LOGO_IMAGE', 'CASL_%s_Logo_212x86.png') ;
define('CASL_THEME_DEFAULT_LEAGUE_LOGO', CASL_THEME_LEAGUE_LOGO_CASL) ;

define('CASL_THEME_OPTION_HIL', 'casllfthdrimg') ;
define('CASL_THEME_OPTION_HIC', 'caslctrhdrimg') ;
define('CASL_THEME_OPTION_HIR', 'caslrghthdrimg') ;
define('CASL_THEME_OPTION_HIL_CSS', 'casllfthdrimgcss') ;
define('CASL_THEME_OPTION_HIC_CSS', 'caslctrhdrimgcss') ;
define('CASL_THEME_OPTION_HIR_CSS', 'caslrghthdrimgcss') ;
define('CASL_THEME_OPTION_LEAGUE_LOGO', 'caslleaguelogo') ;
define('CASL_THEME_OPTION_LEAGUE_LOGO_CSS', 'caslleaguelogocss') ;
define('CASL_THEME_OPTION_BLOG_TITLE_CSS', 'casltitlcss') ;
define('CASL_THEME_OPTION_BLOG_TAGLINE_CSS', 'casltaglincss') ;

//  Default theme options

define('CASL_THEME_OPTION_HIL_DEFAULT', '') ;
define('CASL_THEME_OPTION_HIC_DEFAULT', '') ;
define('CASL_THEME_OPTION_HIR_DEFAULT', '') ;
define('CASL_THEME_OPTION_HIL_CSS_DEFAULT', '') ;
define('CASL_THEME_OPTION_HIC_CSS_DEFAULT', '') ;
define('CASL_THEME_OPTION_HIR_CSS_DEFAULT', '') ;
define('CASL_THEME_OPTION_LEAGUE_LOGO_DEFAULT', CASL_THEME_LEAGUE_LOGO_CASL) ;
define('CASL_THEME_OPTION_LEAGUE_LOGO_CSS_DEFAULT', '') ;
define('CASL_THEME_OPTION_BLOG_TITLE_CSS_DEFAULT', '') ;
define('CASL_THEME_OPTION_BLOG_TAGLINE_CSS_DEFAULT', '') ;

/*
 * Test for empty side bar - code adapted (changed coding style) from this
 * thread on Wordpress.org:  http://wordpress.org/support/topic/251790
 *
 */
function casl_is_sidebar_active($index = 1)
{
	global $wp_registered_sidebars ;

    if (is_int($index ))
    {
		$index = "sidebar-$index" ;
    }
    else
    {
		$index = sanitize_title($index) ;

        foreach ((array)$wp_registered_sidebars as $key => $value)
        {
            if (sanitize_title($value['name']) == $index)
            {
				$index = $key ;
				break ;
            }
        }
    }

	$sidebars_widgets = wp_get_sidebars_widgets() ;

    if (empty($wp_registered_sidebars[$index]) ||
        !array_key_exists($index, $sidebars_widgets) ||
        !is_array( $sidebars_widgets[$index]) ||
        empty($sidebars_widgets[$index]))
    {
		return false ;
    }
	else
    {
		return true ;
    }
}

/**
 * Enqueue any external libraries and CSS needed to support admin options.
 *
 * @return - void
 */
function casl_theme_enqueue_admin()
{
    //  Load jQuery UI Accordion

    //  The jQuery accordion function is not shipped with WordPress so
    //  we need to load it from the Goolge CDN.  Since we're going to load
    //  the jQuery Accordion, we'll load the rest of the jQuery modules we
    //  need from the Google CDN as well to make sure they are all compatible.

    //  This really needs to be limited to just the Theme Options page but for now ...

    wp_deregister_script('jquery', 'jquery-ui-core', 'jquery-ui-accordion');
    wp_register_script('jquery',
        'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', array(), false, false);
    wp_register_script('jquery-ui',
        'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js', array('jquery'), false, true);
    wp_enqueue_script('jquery');
    wp_enqueue_script('jquery-ui');
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-accordion');
    wp_enqueue_style('accordion-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css') ; 
}

//add_action('admin_init', 'casl_theme_enqueue_admin') ;

/**
 * Enqueue any external libraries and CSS needed to support theme.
 *
 * @return - void
 */
function casl_theme_enqueue()
{
    //  Reuqest the shipping version of jQuery be loaded
    //  as it is necessary to support the SuperFish menus.

    wp_enqueue_script('jquery') ;

    //  Load Superfish menus - it comes from within the theme

    $superfish = "%s/js/superfish-1.4.8/js/superfish.js" ;
    $hoverIntent = "%s/js/superfish-1.4.8/js/hoverIntent.js" ;
    $sfmenu = "%s/js/sf-menu.js" ;

    wp_enqueue_script('hoverIntent',
        sprintf($hoverIntent, CASLTHEMEPATH), array('jquery')) ;
    wp_enqueue_script('superfish',
        sprintf($superfish, CASLTHEMEPATH), array('jquery')) ;
    wp_enqueue_script('sfmenu',
        sprintf($sfmenu, CASLTHEMEPATH), array('jquery')) ;

    //  Load the CSS based on the theme options

    $theme_url = dirname(get_bloginfo('stylesheet_url')) ;

    $superfish_css = sprintf("%s/css/superfish.css", $theme_url) ;

    $theme_css = sprintf("%s/css/casl-soccer.css", $theme_url) ;

    //var_dump($bg_image_size_css) ;

    wp_register_style('superfishcss', $superfish_css) ; 
    wp_enqueue_style( 'superfishcss') ;

    wp_register_style('casl-soccer-css', $theme_css) ; 
    wp_enqueue_style( 'casl-soccer-css') ;
}

//  Hook in a redirect action for the template to the enqueue will run

add_action('template_redirect','casl_theme_enqueue');

/**
 * filter to add a theme footer
 *
 */
function casl_theme_footer()
{
    printf("Copyright &copy; 2009-%s, %s - All rights reserved.",
        date('Y'), get_bloginfo('blogtitle')) ;
}

//  Hook in a action for the template to the enqueue will run

add_action('wp_footer','casl_theme_footer');

//  Set up theme options - allows theme
//  to be configured with a color scheme
//  and male, female, or co-ed silhouettes

add_action('admin_menu', 'casl_theme_options_page');

/**
 * Sandbox CASL Theme options page hook
 */
function casl_theme_options_page()
{
    $casl_theme_options_page = add_theme_page('casl',
        'CASL Soccer Theme', 'edit_themes', basename(__FILE__),
        'casl_theme_set_options');

    //  Define the contextual help.
    if ($casl_theme_options_page)
        add_contextual_help($casl_theme_options_page, casl_theme_options_contextual_help()) ;

    //  Only load the scripts we need when on the theme options page.
    add_action('load-' . $casl_theme_options_page, 'casl_theme_enqueue_admin') ;
}

/**
 * casl_theme_options_contextual_help()
 *
 * Build contextual help to be displayed when on the theme options page.
 *
 * @return sting - contextual help.
 */
function casl_theme_options_contextual_help()
{
    $ch = '<h2>CASL Soccer Theme</h2>' ;
    $ch .= '<p>Choose the desired league and optionally add one to three images to the' ;
    $ch .= 'header using the Drag and Drop Media Library.  You can upload an image to the' ;
    $ch .= 'Media Library for it to be available.  If you know CSS, you can tweak the ' ;
    $ch .= 'appearance of the header to meet your needs.' ;

    return $ch ;
}


/**
 * get current casl theme options
 *
 */
function casl_theme_get_options()
{
    $theme_options = array() ;

    //  Header Image Left Option
    $option = get_option(CASL_THEME_OPTION_HIL) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIL] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIL] = CASL_THEME_OPTION_HIL_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIL, CASL_THEME_OPTION_HIL_DEFAULT) ;
    }
    
    //  Header Image Center Option
    $option = get_option(CASL_THEME_OPTION_HIC) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIC] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIC] = CASL_THEME_OPTION_HIC_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIC, CASL_THEME_OPTION_HIC_DEFAULT) ;
    }
    
    //  Header Image Right Option
    $option = get_option(CASL_THEME_OPTION_HIR) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIR] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIR] = CASL_THEME_OPTION_HIR_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIR, CASL_THEME_OPTION_HIR_DEFAULT) ;
    }
    
    //  Header Image Left CSS Option
    $option = get_option(CASL_THEME_OPTION_HIL_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIL_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIL_CSS] = CASL_THEME_OPTION_HIL_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIL_CSS, CASL_THEME_OPTION_HIL_CSS_DEFAULT) ;
    }
    
    //  Header Image Center CSS Option
    $option = get_option(CASL_THEME_OPTION_HIC_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIC_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIC_CSS] = CASL_THEME_OPTION_HIC_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIC_CSS, CASL_THEME_OPTION_HIC_CSS_DEFAULT) ;
    }
    
    //  Header Image Right CSS Option
    $option = get_option(CASL_THEME_OPTION_HIR_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_HIR_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_HIR_CSS] = CASL_THEME_OPTION_HIR_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_HIR_CSS, CASL_THEME_OPTION_HIR_CSS_DEFAULT) ;
    }
    
    //  League Logo
    $option = get_option(CASL_THEME_OPTION_LEAGUE_LOGO) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO] = CASL_THEME_OPTION_LEAGUE_LOGO_DEFAULT ;
        update_option(CASL_THEME_OPTION_LEAGUE_LOGO, CASL_THEME_OPTION_LEAGUE_LOGO_DEFAULT) ;
    }

    //  League Logo CSS
    $option = get_option(CASL_THEME_OPTION_LEAGUE_LOGO_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO_CSS] = CASL_THEME_OPTION_LEAGUE_LOGO_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_LEAGUE_LOGO_CSS, CASL_THEME_OPTION_LEAGUE_LOGO_CSS_DEFAULT) ;
    }

    //  Blog Title CSS
    $option = get_option(CASL_THEME_OPTION_BLOG_TITLE_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_BLOG_TITLE_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_BLOG_TITLE_CSS] = CASL_THEME_OPTION_BLOG_TITLE_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_BLOG_TITLE_CSS, CASL_THEME_OPTION_BLOG_TITLE_CSS_DEFAULT) ;
    }

    //  Tag Line CSS
    $option = get_option(CASL_THEME_OPTION_BLOG_TAGLINE_CSS) ;

    //  If option isn't stored in the database, use the default
    if ($option)
    {
        $theme_options[CASL_THEME_OPTION_BLOG_TAGLINE_CSS] = $option ;
    }
    else
    {
        $theme_options[CASL_THEME_OPTION_BLOG_TAGLINE_CSS] = CASL_THEME_OPTION_BLOG_TAGLINE_CSS_DEFAULT ;
        update_option(CASL_THEME_OPTION_BLOG_TAGLINE_CSS, CASL_THEME_OPTION_BLOG_TAGLINE_CSS_DEFAULT) ;
    }

    return $theme_options ;
}


/**
 * Build Header Image Drag and Drop
 *
 * @param $filler - string - filler to add to ids and classes.
 */
function casl_header_image_drag_n_drop($filler)
{
    $thumbnail_scale = 0.67 ;
    $thumbnail_width = get_option('thumbnail_size_w') * $thumbnail_scale ;
    $thumbnail_height = get_option('thumbnail_size_h') * $thumbnail_scale ;
 
    //  Build the drag zone - don't include the existing image if set

    printf("<div class=\"demo ui-widget ui-helper-clearfix\">\n") ;

    printf("<ul id=\"casl%shdrgallery\" class=\"gallery ui-helper-reset ui-helper-clearfix\">\n", $filler) ;

    $images = &get_children('post_type=attachment&post_mime_type=image') ;

    if (!empty($images))
    {
        foreach ( $images as $attachment_id => $attachment )
        {
            $thumb = wp_get_attachment_image_src($attachment_id) ;
            $image = wp_get_attachment_image_src($attachment_id, 'full') ;
    
            printf("<li id=\"casl%shdrimg-%s\" class=\"ui-widget-content ui-corner-tr\">\n", $filler, $attachment_id) ;
            printf("<h5 class=\"ui-widget-header\">%sx%s</h5>\n", $image[1], $image[2]) ;
            printf("<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"%s\"/>\n", $thumb[0], $thumbnail_width, $thumbnail_height, basename($image[0])) ;
       
            printf("<a href=\"%s\" title=\"%s\" class=\"ui-icon ui-icon-zoomin\">View larger</a>\n", $image[0], basename($image[0])) ;
            printf("<a href=\"%s\" title=\"Select Image\" class=\"ui-icon ui-icon-check\">Remove Image</a>\n</li>\n", $image[0]) ;
        }
    }

    //  Build the drop zone and handle exisitng image if set

    printf("</ul><div id=\"casl%shdrimg\" class=\"ui-widget-content ui-state-default\">\n", $filler) ;
    printf("<h4 class=\"ui-widget-header\"><span class=\"ui-icon ui-icon-check\">Left Header Image</span>Image</h4>\n</div>\n");

    printf("</div><!-- End DnD block -->\n") ;
}

/**
 * casl theme options page form
 *
 */
function casl_theme_set_options()
{
    $theme_options = casl_theme_get_options() ;

    //print_r($theme_options) ;

    $casl_theme_league_logo_options = array(
        CASL_THEME_LEAGUE_LOGO_CASL => CASL_THEME_LEAGUE_LOGO_CASL
       ,CASL_THEME_LEAGUE_LOGO_RECREATIONAL => CASL_THEME_LEAGUE_LOGO_RECREATIONAL
       ,CASL_THEME_LEAGUE_LOGO_CHALLENGE => CASL_THEME_LEAGUE_LOGO_CHALLENGE
       ,CASL_THEME_LEAGUE_LOGO_CLASSIC => CASL_THEME_LEAGUE_LOGO_CLASSIC
       ,CASL_THEME_LEAGUE_LOGO_YTS => CASL_THEME_LEAGUE_LOGO_YTS
       ,CASL_THEME_LEAGUE_LOGO_AMBASSADORS => CASL_THEME_LEAGUE_LOGO_AMBASSADORS
   ) ;

    $casl_theme_thumbnails = array() ;

    $url = dirname(get_bloginfo('stylesheet_url')) ;

    foreach ($casl_theme_league_logo_options as $league)
    {
        $img = sprintf("%s/images/CASL/%s", $url,
            sprintf(CASL_THEME_LEAGUE_LOGO_IMAGE, $league)) ;
        $casl_theme_logos[$league] = $img ;
    }

    //  Default thumbnails are big, add a scaling factor which
    //  will become an theme option setting in the future.

    $thumbnail_scale = 0.67 ;
    $thumbnail_width = get_option('thumbnail_size_w') * $thumbnail_scale ;
    $thumbnail_height = get_option('thumbnail_size_h') * $thumbnail_scale ;

?>
<div class="wrap">

<style type="text/css">
/* Drag and Drop */
#droppable, #header-image-left, #header-image-center, #header-image-right { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
.draggable-image, #draggable, #draggable-nonvalid { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }

/* Gallery Control */
.gallery.custom-state-active { background: #eee; }
.gallery li { float: left; width: <?php echo $thumbnail_width . "px"?>; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; }
.gallery li h5 { margin: 0 0 0.4em; cursor: move; }
.gallery li a { float: right; }
.gallery li a.ui-icon-zoomin { float: left; }
.gallery li img { width: 100%; cursor: move; }

/* Left Header Image */
#casllfthdrgallery { float: left; width: 75%; min-height: 12em; } * html #casllfthdrgallery { height: 12em; } /* IE6 */
#casllfthdrimg { float: right; width: 20%; min-height: 12em; padding: 1%; text-align: center; margin: 0 auto;} * html #casllfthdrimg { height: 18em; } /* IE6 */
#casllfthdrimg h4 { line-height: 20px; margin: 0 0 0.4em; }
#casllfthdrimg h4 .ui-icon { float: left; }
#casllfthdrimg .gallery h5 { display: none; }

/* Center Header Image */
#caslctrhdrgallery { float: left; width: 75%; min-height: 12em; } * html #caslctrhdrgallery { height: 12em; } /* IE6 */
#caslctrhdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #caslctrhdrimg { height: 18em; } /* IE6 */
#caslctrhdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#caslctrhdrimg h4 .ui-icon { float: left; }
#caslctrhdrimg .gallery h5 { display: none; }

/* Right Header Image */
#caslrghthdrgallery { float: left; width: 75%; min-height: 12em; } * html #caslrghthdrgallery { height: 12em; } /* IE6 */
#caslrghthdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #caslrghthdrimg { height: 18em; } /* IE6 */
#caslrghthdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#caslrghthdrimg h4 .ui-icon { float: left; }
#caslrghthdrimg .gallery h5 { display: none; }

</style>

<br clear="all"/>

    <div id="icon-options-general" class="icon32"><br /></div>
    <h2>CASL Theme Options</h2>
    <form name="casl_theme_options" method="post" action="options.php">
    <?php wp_nonce_field('update-options') ; ?>
    <div id="options-accordion">
        <div><h3><a href="#">Left Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("lft") ; ?>
        </div>
        <div><h3><a href="#">Center Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("ctr") ; ?>
        </div>
        <div><h3><a href="#">Right Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("rght") ; ?>
        </div>
        <div><h3><a href="#">CSS Overrides</a></h3>
            <div>
                <h4>Blog Title</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_BLOG_TITLE_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_BLOG_TITLE_CSS] ?>"/>
                <h4>Blog Tagline</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_BLOG_TAGLINE_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_BLOG_TAGLINE_CSS] ?>"/>
                <h4>CASL League Logo Block</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_LEAGUE_LOGO_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO_CSS] ?>"/>
                <h4>Left Header Image Block</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_HIL_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIL_CSS] ?>"/>
                <h4>Center Header Image Block</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_HIC_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIC_CSS] ?>"/>
                <h4>Right Header Image Block</h4>
                <input size="60" type="text" name="<?php echo CASL_THEME_OPTION_HIR_CSS; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIR_CSS] ?>"/>
            </div>
        </div>
            <div>
                <h3><a href="#">CASL League</a></h3>
                <div>
<table class="widefat fixed" style="margin: 10px 0px;" cellspacing="0">
    <tbody id="the-list" class="list:post">
<?php
    $tdctr = 0 ;

    foreach ($casl_theme_logos as $key => $value)
    {
        //var_dump(strtolower($key) === $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO]) ;
        $checked = ($key == $theme_options[CASL_THEME_OPTION_LEAGUE_LOGO]) ? " checked=\"checked\"" : "" ;

        //  New row?  If so, open the row.
        if ($tdctr == 0)
        {
            $tdctr = 0 ;
            print "<tr valign=\"middle\">" ;
        }

        printf("<td style=\"padding: 10px 5px;\" align=\"center\"><img src=\"%s\" alt=\"%s\"><br/>", $value, basename($value)) ;
        printf("<input type='radio' name='%s' value=\"%s\"%s />", CASL_THEME_OPTION_LEAGUE_LOGO, $key, $checked) ;
        printf("&nbsp;&nbsp;<strong>%s</strong></td>", $key) ;

        //  End the row after 2 columns
        if (++$tdctr == 2)
        {
            $tdctr = 0 ;
            print "</tr>" ;
        }
    }

    //  Partial row?
    if ($tdctr != 2) print "</tr>" ;
?>
    </tbody>
</table>
</div>
            </div>
        </div>

  <input type="hidden" name="casllfthdrimg" value="<?php echo $theme_options[CASL_THEME_OPTION_HIL]; ?>" />
  <input type="hidden" name="caslctrhdrimg" value="<?php echo $theme_options[CASL_THEME_OPTION_HIC]; ?>" />
  <input type="hidden" name="caslrghthdrimg" value="<?php echo $theme_options[CASL_THEME_OPTION_HIR]; ?>" />
  <input type="hidden" name="action" value="update" />
  <input type="hidden" name="page_options" value="<?php printf("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s", CASL_THEME_OPTION_HIL, CASL_THEME_OPTION_HIC, CASL_THEME_OPTION_HIR, CASL_THEME_OPTION_HIL_CSS, CASL_THEME_OPTION_HIC_CSS, CASL_THEME_OPTION_HIR_CSS, CASL_THEME_OPTION_BLOG_TITLE_CSS, CASL_THEME_OPTION_BLOG_TAGLINE_CSS, CASL_THEME_OPTION_LEAGUE_LOGO, CASL_THEME_OPTION_LEAGUE_LOGO_CSS) ?>" />
  <p class="submit">
  <input type="submit" name="Submit" class="button-primary" value="Save Changes" />
  </p>
  </form>
  </div>

<script type="text/javascript">

//
//  This jQuery/jQuery UI code was derived from the
//  jQuery UI Simple Photo Manager Example found at:
//
//  http://jqueryui.com/demos/droppable/#photo-manager
//
//  This Javascript allows the user to select images from
//  the media library to be used in the thene header using
//  a drag and drop implementation.
//

jQuery(document).ready(function($) {
    //  Set up the accordion and set the first section to be open
    $("#options-accordion").accordion({header: "h3", active: 4, autoHeight: true});

    // set up the left header image gallery and container
    var $casllfthdrcntr = false ;
    var $casllfthdrimg = $('#casllfthdrimg');
    var $casllfthdrgallery = $('#casllfthdrgallery');

    // set up the center header image gallery and container
    var $caslctrhdrcntr = false ;
    var $caslctrhdrimg = $('#caslctrhdrimg');
    var $caslctrhdrgallery = $('#caslctrhdrgallery');

    // set up the right header image gallery and container
    var $caslrghthdrcntr = false ;
    var $caslrghthdrimg = $('#caslrghthdrimg');
    var $caslrghthdrgallery = $('#caslrghthdrgallery');

    // let the left header gallery items be draggable
    $('li',$casllfthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the left header image be droppable, accepting the gallery items
    $casllfthdrimg.droppable({
        accept: '#casllfthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the left gallery be droppable as well,
    // accepting items from the left header image
    $casllfthdrgallery.droppable({
        accept: '#casllfthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center header gallery items be draggable
    $('li',$caslctrhdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
        });

    // let the center header image be droppable,
    // accepting the gallery items
    $caslctrhdrimg.droppable({
        accept: '#caslctrhdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center gallery be droppable as well,
    // accepting items from the left header image
    $caslctrhdrgallery.droppable({
        accept: '#caslctrhdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // let the center header gallery items be draggable
    $('li',$caslrghthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the right header image be droppable,
    // accepting the gallery items
    $caslrghthdrimg.droppable({
        accept: '#caslrghthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the right gallery be droppable as well,
    // accepting items from the left header image
    $caslrghthdrgallery.droppable({
        accept: '#caslrghthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // image deletion function
    var recycle_icon = '<a href="#" title="Remove Image" class="ui-icon ui-icon-trash">Remove Image</a>';

    function selectImage($item, $attrid) {
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;

        switch (galleryId)
        {
            case "casllfthdrimg" :
                hdrimg = $casllfthdrimg;
                break;
 
            case "caslctrhdrimg" :
                hdrimg = $caslctrhdrimg;
                break;
 
            case "caslrghthdrimg" :
                hdrimg = $caslrghthdrimg;
                break;
        }
 
        $item.fadeOut(function() {
            var $list = $('ul',hdrimg).length ? $('ul',hdrimg) : $('<ul class="gallery ui-helper-reset"/>').appendTo(hdrimg);

            $item.find('a.ui-icon-check').remove();
            $item.append(recycle_icon).appendTo($list).fadeIn(function() {
                $item.animate({ width: '<?php echo $thumbnail_width . "px" ?>' }).find('img').animate({ height: '<?php echo $thumbnail_height . "px" ?>' });
        return ;
            });
        });

        hdrimg.droppable('disable');

        switch (galleryId)
        {
            case "casllfthdrimg" :
                $casllfthdrcntr = true ;
                break;
 
            case "caslctrhdrimg" :
                $caslctrhdrcntr = true;
                break;
 
            case "caslrghthdrimg" :
                $caslrghthdrcntr = true;
                break;
        }
 
        // Save it in the hidden input
        $("input[name='" + galleryId + "']").val(imageId);
    }

    // image recycle function
    var trash_icon = '<a href="#" title="Select Image" class="ui-icon ui-icon-check">Select Image</a>';
    function removeImage($item, $attrid) {
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;
        var hdrgallery = null;

        switch (galleryId)
        {
            case "casllfthdrimg" :
                hdrimg = $casllfthdrimg;
                hdrgallery = $casllfthdrgallery;
                break;
 
            case "caslctrhdrimg" :
                hdrimg = $caslctrhdrimg;
                hdrgallery = $caslctrhdrgallery;
                break;
 
            case "caslrghthdrimg" :
                hdrimg = $caslrghthdrimg;
                hdrgallery = $caslrghthdrgallery;
                break;
        }
 
        $item.fadeOut(function() {
            $item.find('a.ui-icon-trash').remove();
            $item.css('width','<?php echo $thumbnail_width . "px" ?>').append(trash_icon).find('img').css('height','<?php echo $thumbnail_height . "px" ?>').end().appendTo(hdrgallery).fadeIn();
        });

        hdrimg.droppable('enable');

        switch (galleryId)
        {
            case "casllfthdrimg" :
                $casllfthdrcntr = false;
                break;
 
            case "caslctrhdrimg" :
                $caslctrhdrcntr = false;
                break;
 
            case "caslrghthdrimg" :
                $caslrghthdrcntr = false;
                break;
        }
 
        $("input[name='" + galleryId + "']").val("");
    }

    // image preview function, demonstrating the ui.dialog used as a modal window
    function viewLargerImage($link) {
        var src = $link.attr('href');
        var title = $link.siblings('img').attr('alt');
        var $modal = $('img[src$="'+src+'"]');

        if ($modal.length) {
            $modal.dialog('open')
        } else {
            var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />').attr('src',src).appendTo('body');
            setTimeout(function() {
                img.dialog({
                    title: title,
                    width: 400,
                    modal: true
                });
            }, 1);
        }
    }

    // resolve the icons behavior with event delegation
    $('ul.gallery > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);

        var hdrcntr = null;
        var gallery = $item.attr('id').split("-", 2)[0];

        switch (gallery)
        {
            case "casllfthdrimg" :
                hdrcntr = $casllfthdrcntr;
                break;
 
            case "caslctrhdrimg" :
                hdrcntr = $caslctrhdrcntr;
                break;
 
            case "caslrghthdrimg" :
                hdrcntr = $caslrghthdrcntr;
                break;
        }

        if ($target.is('a.ui-icon-check')) {
            if (hdrcntr) {
                $item.fadeOut('slow', function() {
                    //$item.appendTo($casllfthdrgallery);
                }) ;
                $item.fadeIn('slow') ;
            }
            else {
                selectImage($item, $item.attr('id'));
            }
        } else if ($target.is('a.ui-icon-zoomin')) {
            viewLargerImage($target);
            } else if ($target.is('a.ui-icon-trash')) {
            removeImage($item, $item.attr('id'));
        }

        return false;
    });


    //  Preload header images?  Need to move any images
    //  that are already set as one of the header images.
 
    //  Left header image preload?
    if ($("input[name='casllfthdrimg']").val() != "") {
        selectImage($("#casllfthdrimg-" +
            $("input[name='casllfthdrimg']").val()), "casllfthdrimg-" +
            $("input[name='casllfthdrimg']").val()) ;
    }

    //  Center header image preload?
    if ($("input[name='caslctrhdrimg']").val() != "") {
        selectImage($("#caslctrhdrimg-" +
            $("input[name='caslctrhdrimg']").val()), "caslctrhdrimg-" +
            $("input[name='caslctrhdrimg']").val()) ;
    }

    //  Right header image preload?
    if ($("input[name='caslrghthdrimg']").val() != "") {
        selectImage($("#caslrghthdrimg-" +
            $("input[name='caslrghthdrimg']").val()), "caslrghthdrimg-" +
            $("input[name='caslrghthdrimg']").val()) ;
    }
});
</script>    

<?php
}

/**
 * Custom Login Screen
 *
 */
function custom_login()
{ 
    printf("<link rel=\"stylesheet\" type=\"text/css\" href=\"%s/css/casl-soccer-login.css\" />", dirname(get_bloginfo('stylesheet_url'))) ;
}
add_action('login_head', 'custom_login');

// Widgets plugin: intializes the plugin after the widgets above have passed snuff
function casl_theme_widgets_init() {
	if ( !function_exists('register_sidebar') )
		return;

	// Formats the CASL Theme widgets, adding readability-improving whitespace
	$p = array(
        'name'           =>   null,
		'before_widget'  =>   "\n\t\t\t" . '<li id="%1$s" class="widget %2$s">',
		'after_widget'   =>   "\n\t\t\t</li>\n",
		'before_title'   =>   "\n\t\t\t\t". '<h3 class="widgettitle">',
		'after_title'    =>   "</h3>\n"
	);

    //  Unregister the sidebars that the Sandbox theme defines

    unregister_sidebar('sidebar-1') ;
    unregister_sidebar('sidebar-2') ;

    //  Build four new sidebars - they are aranged where the
    //  North spans two columns, East and West each occupy one
    //  column, and South spans two columns.

    $p['name'] = "North Sidebar";
    register_sidebar($p) ;

    $p['name'] = "West Sidebar";
    register_sidebar($p) ;

    $p['name'] = "East Sidebar";
    register_sidebar($p) ;

    $p['name'] = "South Sidebar";
    register_sidebar($p) ;

    //  Define new sidebars that  span the header and footer

    $p['name'] = "Header Sidebar";
    register_sidebar($p) ;

    $p['name'] = "Footer Sidebar";
    register_sidebar($p) ;

    $p['name'] = "Sponsor Sidebar";
    register_sidebar($p) ;
}

// Runs our code at the end to check that everything needed has loaded
add_action( 'init', 'casl_theme_widgets_init' );

/**
 * Facebook integration
 *
 */
function casl_theme_facebook_connect()
{ 
    if (function_exists('fbc_is_configured') && fbc_is_configured())
    {
        if (is_user_logged_in())
        {
            fbc_display_login_state() ;
        }
        else
        {
            $user = wp_get_current_user();

            //  For the moment disallow connecting existing accounts
            if ($user->ID) return ;

            $button = render_fbconnect_button() ;
            echo "<li>$button</li>" ;

        }
    }
}

//  Hook in the Facebook integration
add_action('wp_meta', 'casl_theme_facebook_connect');

/**
 * the_content filter - this filter adds support for
 * wp-print, wp-postviews, and a minimum height for the
 * .hentry class when a single post or page is displayed.
 *
 * @param string - content
 * @return string - filtered content
 */
function casl_theme_the_content_filter($content)
{
    //  Define min-height for .hentry?

    if (is_single())
    {
?>
<style>
.hentry {
    min-height: 600px;
}
</style>
<?php
    }

    //  Support for wp-print
    if (function_exists('print_link'))
    {
        $content .= "<div class=\"print-link\">[print_link]</div><br style=\"clear: both;\" />" ;
    }

    //  Support for wp-postviews
    if(function_exists('the_views'))
    {
        $views = the_views(false) ;
        if (intval(post_custom('views')) == 1)
            $views = substr($views, 0, strlen($view) - 1) ;

        $content .= sprintf("<div class=\"post-views\">%s</div><br style=\"clear: both;\" />", $views) ;
    }

    return $content ;
}
add_filter('the_content', 'casl_theme_the_content_filter') ;
?>
